import React, { useState, useEffect, useRef } from "react";
import { Table, Button, Modal, Switch } from "antd";
import axios from "axios";
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import UserForm from "../../../components/user-manage/UserForm";
export default function UserList() {
  const [dataSource, setdataSource] = useState([]);
  const [open, setOpen] = useState(false);
  const [roleList, setroleList] = useState([]);
  const [regionList, setregionList] = useState([]);
  const [isUpdateVisible, setisUpdateVisible] = useState(false);
  const [isUpdataDisable, setisUpdataDisable] = useState(false);
  const [current, setcurrent] = useState(null);
  const addForm = useRef(null);
  const updataForm = useRef(null);
  const { roleId, region, username } = JSON.parse(
    localStorage.getItem("token")
  );
  const roleObj = {
    1: "superadmin",
    2: "admin",
    3: "editor",
  };
  useEffect(() => {
    axios.get("/users?_expand=role").then((res) => {
      const list = res.data;
      setdataSource(
        roleObj[roleId] === "superadmin"
          ? list
          : [
              ...list.filter((item) => item.username === username),
              ...list.filter(
                (item) =>
                  item.region === region && roleObj[item.roleId] === "editor"
              ),
            ]
      );
    });
  }, []);
  useEffect(() => {
    axios.get("/regions").then((res) => {
      setregionList(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get("/roles").then((res) => {
      setroleList(res.data);
    });
  }, []);
  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      filters: [
        ...regionList.map((item) => ({
          text: item.title,
          value: item.value,
        })),
        { text: "全球", value: "" },
      ],
      onFilter: (value, item) => item.region === value,
      render(region) {
        return <b>{region === "" ? "全球" : region}</b>;
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role.roleName;
      },
    },
    {
      title: "用户名",
      dataIndex: "username",
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={() => {
              switchMethod(item);
            }}
          ></Switch>
        );
      },
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            <Button
              danger
              shape="circle"
              onClick={() => {
                confirmMethod(item);
              }}
              disabled={item.default}
              icon={<DeleteOutlined />}
            />
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              disabled={item.default}
              onClick={() => {
                handleUpdata(item);
              }}
            />
          </div>
        );
      },
    },
  ];
  const handleUpdata = (item) => {
    setisUpdateVisible(true);
    setcurrent(item);
    //确保同步更新
    setTimeout(() => {
      if (item.roleId === 1) {
        setisUpdataDisable(true);
      } else {
        setisUpdataDisable(false);
      }
      updataForm.current.setFieldsValue(item);
    }, 0);
  };
  const switchMethod = (item) => {
    item.roleState = !item.roleState;
    setdataSource([...dataSource]);
    axios
      .patch(`/users/${item.id}`, {
        roleState: item.roleState,
      })
      .then((res) => {});
  };
  const deteleMethod = (item) => {
    setdataSource(dataSource.filter((data) => data.id !== item.id));
  };
  const confirmMethod = (item) => {
    Modal.confirm({
      title: "你确定要删除吗？",
      icon: <ExclamationCircleOutlined />,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        deteleMethod(item);
      },
    });
  };
  const addFormOk = () => {
    addForm.current
      .validateFields()
      .then((value) => {
        setOpen(false);
        addForm.current.resetFields();
        axios
          .post(`/users`, {
            ...value,
            roleState: true,
            default: false,
          })
          .then((res) => {
            console.log(res.data);
            setdataSource([...dataSource, res.data]);
          });
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };
  const updataFormOk = () => {
    updataForm.current
      .validateFields()
      .then((value) => {
        setisUpdateVisible(false);
        setdataSource(
          dataSource.map((item) => {
            if (item.id === current.id) {
              return {
                ...item,
                ...value,
                role: roleList.filter((data) => data.id === value.roleId)[0],
              };
            }
            return item;
          })
        );
        setisUpdataDisable(!isUpdataDisable);
        axios.patch(`/users/${current.id}`, value);
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };
  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setOpen(true);
        }}
      >
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{ pageSize: 5 }}
        rowKey={(item) => item.id}
      />
      <Modal
        open={open}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setOpen(false);
        }}
        onOk={() => {
          addFormOk();
        }}
      >
        <UserForm
          region={regionList}
          roleList={roleList}
          ref={addForm}
        ></UserForm>
      </Modal>

      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false);
        }}
        onOk={() => {
          updataFormOk();
        }}
      >
        <UserForm
          region={regionList}
          roleList={roleList}
          ref={updataForm}
          isUpdataDisable={isUpdataDisable}
          isupdata={true}
        ></UserForm>
      </Modal>
    </div>
  );
}
